package com.jiamao.goplay.ui.login.vm;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResImage;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.main.MainActivity;
import com.jiamao.goplay.util.AliOSSUpload;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.tamsiree.rxkit.RxImageTool;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.view.RxToast;

import java.io.File;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class AddHeadImageModel extends BaseViewModel<DataRepository> {

    public ObservableField<String> image = new ObservableField<>("");
    public ObservableField<String> nickName = new ObservableField<>("");
    public ObservableField<String> birthday = new ObservableField<>("");
    public ObservableField<String> constellations = new ObservableField<>("");
    public ObservableField<String> sex = new ObservableField<>("");

    public AddHeadImageModel(@NonNull Application application, DataRepository model) {
        super(application, model);

        Messenger.getDefault().register(this, Config.MGER_PHOTO_LOGIN,  String.class, new BindingConsumer<String>() {
            @Override
            public void call(String path) {


                uc.image.setValue(path);
              //  uc.pSwitchEvent.setValue("");
            }
        });


    }


    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> showTime = new SingleLiveEvent<>();
        public SingleLiveEvent<String> image = new SingleLiveEvent<>();

    }

    //下一步按钮点击时间
    public BindingCommand nextButtonOnclickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (TextUtils.isEmpty(image.get()) || TextUtils.isEmpty(nickName.get()) || TextUtils.isEmpty(birthday.get())
            || TextUtils.isEmpty(constellations.get()) || TextUtils.isEmpty(sex.get()))
            {
                RxToast.showToastShort("请输入完整参数");
                return;
            }


                model.getApi().regiestUserInfo(nickName.get(),birthday.get(),sex.get().equals("男")?"1":"0",image.get())
                        .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                        .compose(RxUtils.schedulersTransformer())  // 线程调度
                        .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                showDialog();
                                // dialog.show();
                            }
                        })
                        .subscribe(new BaseSubscriber<BaseRep>() {

                            @Override
                            public void onError(Throwable throwable) {
                                //关闭对话框
                                dismissDialog();
                                //请求刷新完成收回
                                RxToast.showToastShort("网络出现故障");
                            }

                            @Override
                            public void onComplete() {
                                dismissDialog();
                            }

                            @Override
                            public void onNext(BaseRep o)   {
                                super.onNext(o);
                                dismissDialog();
                                if (o.isOk()){
                                    Log.d("HTML","UID:"+model.getmLocalDataSource().getUid()+"  token:"+ model.getmLocalDataSource().getIMToken());
                                    KLog.d("html"," aa  "+model.getmLocalDataSource().getUid());
                                    LoginInfo info = new LoginInfo(model.getmLocalDataSource().getUid()+"",model.getmLocalDataSource().getIMToken());

                                    SPUtils.getInstance().put(Config.SEX, sex.get().equals("男")?1:0);

                                    KLog.d("sex:"+sex.get()+"  sex:"+SPUtils.getInstance().getInt(Config.SEX));
                                    RequestCallback<LoginInfo> callback =
                                            new RequestCallback<LoginInfo>() {
                                                @Override
                                                public void onSuccess(LoginInfo param) {
                                                    LogUtil.i("HTML", "im login success");
                                                    SPUtils.getInstance().put(Config.IS_LOGIN,true);
                                                    startActivity(MainActivity.class);
                                                    finish();
                                                    // your code
                                                }

                                                @Override
                                                public void onFailed(int code) {
                                                    RxToast.showToastShort("IM服务器登陆失败");
                                                    LogUtil.i("HTML", "im onFailed "+code);
                                                }

                                                @Override
                                                public void onException(Throwable exception) {
                                                    // your code
                                                    RxToast.showToastShort("IM 登录异常"+exception.getMessage());
                                                }
                                            };
                                    //执行手动登录
                                    NIMClient.getService(AuthService.class).login(info).setCallback(callback);

                                }else {
                                    RxToast.showToastShort(o.getMsg());
                                }
                            }
                        });



//            startActivity(MainActivity.class);
//            finish();
        }
    });

    //下一步按钮点击时间
    public BindingCommand PhotoButtonOnclickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
        //    uc.showSex.setValue(false);

            uc.showTime.setValue(false);

        }
    });


    public void uploadImage(String path){


        File file = new File(path);
        //上传图片需要MultipartBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("File", file.getName(), requestBody);

//        // 构造上传请求。
//        PutObjectRequest put = new PutObjectRequest("<bucketName>", "<objectName>", "<uploadFilePath>");
//
//// 文件元信息的设置是可选的。
//// ObjectMetadata metadata = new ObjectMetadata();
//// metadata.setContentType("application/octet-stream"); // 设置content-type。
//// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // 校验MD5。
//// put.setMetadata(metadata);
//
//
//        AliOSSUpload.getInstance().uploadImage(path);
        RequestBody param = RequestBody.create(MediaType.parse("text/plain"), 0+"");
        model.getApi().uploadImage(body,param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResImage>>() {

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        //请求刷新完成收回
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }

                    @Override
                    public void onNext(BaseRep<ResImage> o)   {

                        super.onNext(o);
                        dismissDialog();
                        Log.d("html", "aaaa " + o.getData().getPath());
                        Log.d("html", "aaaa " + o.getData().toString());

                        uc.image.setValue(o.getData().getPath());

                        if (o.isOk()){
                            uc.image.setValue(o.getData().getPath());

                        }else {
                            RxToast.showToastShort(o.getMsg());
                        }
                    }
                });



    }





}
